package org.itzixi;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.itzixi.netty.http.HttpHandler;
import org.itzixi.netty.http.HttpServerInitializer;
import org.itzixi.netty.utils.JedisPoolUtils;
import org.itzixi.netty.utils.ZKUtil;
import org.itzixi.netty.websocket.WSServerInitializer;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
public class ChatServer {
    private static final String initOnlineCounts = "0";
    private static final Jedis jedis = JedisPoolUtils.getJedis();

    public static int selectPort(int port){
        String portKey = "netty_port";
        Map<String, String> map = jedis.hgetAll(portKey);
        System.out.println("map = " + map);


        List<Integer> portList = map.entrySet().stream().map(Map.Entry::getKey)
                .map(Integer::parseInt).collect(Collectors.toList());
        System.out.println("portList = " + portList);
        int nettyPort = -1;
        if (CollectionUtils.isEmpty(portList)){
            jedis.hset(portKey, port + "", initOnlineCounts);
            nettyPort = port;
        } else {
            int currPort = portList.stream().max(Integer::compareTo).get() + 10;
            jedis.hset(portKey, currPort + "", initOnlineCounts);
            nettyPort = currPort;
        }
        return nettyPort;
    }

    // netty启动的时候，从redis查找有没有端口，如果没有则使用默认的875端口，如果有则累加10


    public static void main(String[] args)  {
        // 接收客户端的链接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        final int nettyDefaultPort = 875;
        int nettPort = selectPort(nettyDefaultPort);

        try {
            String localIP = ZKUtil.getLocalIP();
            log.info("本机ip地址:{}",localIP);
            // 把chat-server注册到zookeeper
            ZKUtil.registerNettyServer("server-list", localIP, nettPort);

            // 构建netty服务器
            ServerBootstrap server = new ServerBootstrap();     // 服务的启动类
            server.group(bossGroup, workGroup)                // 把主从线程池组放入到启动类中
                    .channel(NioServerSocketChannel.class)      // 设置Nio的双向通道
                    .childHandler(new WSServerInitializer());   // 设置处理器，用于处理workerGroup


            ChannelFuture channelFuture = server.bind(nettPort).sync();
            // 监听关闭的channel
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}